package com.tunnel.home.rest;

import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.axe.annotation.ioc.Autowired;
import org.axe.annotation.ioc.Controller;
import org.axe.annotation.mvc.Request;
import org.axe.annotation.mvc.RequestParam;
import org.axe.constant.RequestMethod;
import org.axe.exception.RestException;

import com.tunnel.home.dao.DomainDao;
import com.tunnel.home.entity.Domain;
import com.tunnel.home.entity.User;

@Controller(basePath="/domain",desc="域名")
public class DomainRest {
	@Autowired
	private DomainDao domainDao;

	@Request(path="/list",method=RequestMethod.GET,desc="我的域名列表")
	public List<Domain> domain_list(User user){
		return domainDao.getList(user.getId());
	}
	
	@Request(path="/post",method=RequestMethod.POST,desc="申请域名")
	public void post(
			@RequestParam(name="domainName",required=true,desc="域名")String domainName,
			User user){
		Pattern pattern = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9]{0,62}(\\.[a-zA-Z0-9][a-zA-Z0-9]{0,62})*$");
		Matcher matcher = pattern.matcher(domainName);
		if(!matcher.find()){
			throw new RestException("域名不合法");
		}
		domainName = domainName.toLowerCase();
		//域名规范要求不超过67个字符，本身.tunnel.cool包括12个字符
		if(domainName.length() > 16){//控制在允许输入16位吧
			throw new RestException("域名过长");
		}
		
		Domain domain = domainDao.get(domainName);
		if(domain != null){
			throw new RestException("域名已被注册，请尝试其他域名");
		}
		
		if(!user.getEmail().equals("1157656909@qq.com")){//特殊待遇
			int count = domainDao.count(user.getId());
			if(count >= 10){
				throw new RestException("抱歉，每个账户最多只允许申请10条域名");
			}
		}
		
		Domain entity = new Domain();
		entity.setName(domainName);
		entity.setUserId(user.getId());
		entity.setCreateTime(new Date());
		domainDao.saveEntity(entity);
	}
	
	@Request(path="/del",method=RequestMethod.DELETE,desc="删除域名")
	public void del(
			@RequestParam(name="domainName",required=true,desc="域名")String domainName,
			User user){
		Domain domain = domainDao.get(domainName);
		if(domain != null && domain.getUserId() != user.getId()){
			throw new RestException("禁止操作");
		}
		if(domain != null){
			domainDao.deleteEntity(domain);
		}
	}
	
}
